/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.restaurant.dto.CommodityRecordDTO;
import org.springblade.modules.restaurant.entity.CommodityRecord;
import org.springblade.modules.restaurant.entity.CommodityRecordRelation;
import org.springblade.modules.restaurant.enums.CommodityRecordStatusEnums;
import org.springblade.modules.restaurant.excel.CommodityRecordRelationExcel;
import org.springblade.modules.restaurant.mapper.CommodityRecordMapper;
import org.springblade.modules.restaurant.service.ICommodityRecordRelationService;
import org.springblade.modules.restaurant.service.ICommodityRecordService;
import org.springblade.modules.restaurant.vo.CommodityRecordVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 货物采购记录 服务实现类
 *
 * @author Blade
 * @since 2025-01-21
 */
@Service
@AllArgsConstructor
public class CommodityRecordServiceImpl extends BaseServiceImpl<CommodityRecordMapper, CommodityRecord> implements ICommodityRecordService {

	private final ICommodityRecordRelationService commodityRecordRelationService;

	@Override
	public IPage<CommodityRecordVO> selectCommodityRecordPage(IPage<CommodityRecordVO> page, CommodityRecordVO commodityRecord) {
		return page.setRecords(baseMapper.selectCommodityRecordPage(page, commodityRecord));
	}

	@Override
	public boolean exportCheck(String startTime, String endTime) {
		return !list(Wrappers.<CommodityRecord>lambdaQuery()
			.eq(CommodityRecord::getStatus, CommodityRecordStatusEnums.WAIT_AUDIT.getStatus())
			.between(CommodityRecord::getCreateTime, startTime, endTime)).isEmpty();
	}

	@Override
	public List<CommodityRecordRelationExcel> exportCommodity(List<CommodityRecordRelation> commodityRecordRelationList, boolean isNullRemark) {
		try {
			if (commodityRecordRelationList.isEmpty()) {
				log.error("商品采购记录关系表数据为空");
				return new ArrayList<>();
			}

			List<CommodityRecordRelation> commodityRecordRelations;
			if (isNullRemark) {
				// 根据商品ID 求和 组成新的对象
				commodityRecordRelations = new ArrayList<>(commodityRecordRelationList.stream()
					.collect(Collectors.groupingBy(CommodityRecordRelation::getCommodityId)).entrySet().stream().map(entry -> {
						CommodityRecordRelation commodityRecordRelation = new CommodityRecordRelation();
						BeanUtil.copyProperties(entry.getValue().get(0), commodityRecordRelation);
						commodityRecordRelation.setCommodityId(entry.getKey());
						commodityRecordRelation.setNumber(entry.getValue().stream().mapToInt(CommodityRecordRelation::getNumber).sum());
						return commodityRecordRelation;
					}).toList());
			} else {
				commodityRecordRelations = new ArrayList<>(commodityRecordRelationList);
			}
			if (commodityRecordRelations.isEmpty()) {
				log.error("商品采购记录关系表数据为空");
				return new ArrayList<>();
			}
			// commodityRecordRelations 根据 sort 排序  会存在分类为空的
			commodityRecordRelations.sort((o1, o2) -> {
				if (o1.getSort() == null) {
					return 1;
				}
				if (o2.getSort() == null) {
					return -1;
				}
				return o1.getSort() - o2.getSort();
			});

			// 转换成excel导出对象
			return commodityRecordRelations.stream().map(commodityRecordRelation -> {
				CommodityRecordRelationExcel item = new CommodityRecordRelationExcel();
				item.setCommodityName(commodityRecordRelation.getCommodityName());
				item.setNumber(commodityRecordRelation.getNumber());
				item.setUnit(commodityRecordRelation.getUnit());
				item.setCategoryName(commodityRecordRelation.getCategoryName());
				item.setRemark(commodityRecordRelation.getRemark());
				return item;
			}).collect(Collectors.toList());
		} catch (Exception e) {
			log.error("导出异常:", e);
			return new ArrayList<>();
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveCommodity(CommodityRecordDTO commodityRecordDTO) {
		long id = IdWorker.getId();
		CommodityRecord commodityRecord = BeanUtil.copyProperties(commodityRecordDTO, CommodityRecord.class);
		commodityRecord.setId(id);
		commodityRecord.setStatus(CommodityRecordStatusEnums.WAIT_AUDIT.getStatus());

		List<CommodityRecordRelation> commodityRecordRelations = commodityRecordDTO.getCommodityRecordRelations();

		// 过滤 number < 1 的数据
		commodityRecordRelations.removeIf(commodityRecordRelation -> commodityRecordRelation.getNumber() < 1);

		commodityRecordRelations.forEach(commodityRecordRelation ->
			{
				commodityRecordRelation.setCommodityRecordId(id);
				commodityRecordRelation.setStatus(CommodityRecordStatusEnums.WAIT_AUDIT.getStatus());
				if (StrUtil.isNotBlank(commodityRecordRelation.getRemark())) {
					String remark = commodityRecord.getUserName() + " : " + commodityRecordRelation.getRemark();
					commodityRecordRelation.setRemark(remark);
				}
			}

		);

		// 获取商品名 逗号隔开 超出500个字符截断
		String commodityNames = commodityRecordRelations.stream()
			.map(CommodityRecordRelation::getCommodityName)
			.collect(Collectors.joining(","));

		if (commodityNames.length() > 500) {
			commodityNames = commodityNames.substring(0, 500);
		}

		commodityRecord.setSummary(commodityNames);
		if (commodityRecordRelations.isEmpty()) {
			log.error("商品采购记录关系表数据为空");
			return false;
		}

		// 保存商品采购记录关系表
		commodityRecordRelationService.saveBatch(commodityRecordRelations);
		// 保存商品采购记录
		return save(commodityRecord);

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean statusUpdate(Long id, Integer status) {

		CommodityRecord commodityRecord = getById(id);
		commodityRecord.setStatus(status);
		updateById(commodityRecord);

		// 更新关联表状态
		return commodityRecordRelationService.lambdaUpdate().set(CommodityRecordRelation::getStatus, status)
			.set(CommodityRecordRelation::getUpdateTime, commodityRecord.getUpdateTime())
			.set(CommodityRecordRelation::getUpdateUser, commodityRecord.getUpdateUser())
			.eq(CommodityRecordRelation::getCommodityRecordId, id).update();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean delDetail(List<Long> detailIds) {
		List<CommodityRecordRelation> commodityRecordRelations = commodityRecordRelationService.listByIds(detailIds);
		if (!commodityRecordRelations.isEmpty()) {
			commodityRecordRelationService.deleteLogic(detailIds);
		}
		commodityRecordRelations.forEach(commodityRecordRelation -> {
			updateSummary(commodityRecordRelation.getCommodityRecordId());
		});
		return true;
	}

	@Override
	public boolean confirm(List<Long> ids) {

		lambdaUpdate().in(CommodityRecord::getId, ids)
			.set(CommodityRecord::getStatus, CommodityRecordStatusEnums.AUDITED.getStatus())
			.update();
		return commodityRecordRelationService.lambdaUpdate().in(CommodityRecordRelation::getCommodityRecordId, ids)
			.set(CommodityRecordRelation::getStatus, CommodityRecordStatusEnums.AUDITED.getStatus())
			.update();
	}

	/**
	 * 更新商品采购记录的摘要
	 *
	 * @param commodityRecordId 商品采购记录ID
	 */
	private void updateSummary(Long commodityRecordId) {
		CommodityRecord commodityRecord = getById(commodityRecordId);
		List<CommodityRecordRelation> commodityRecordRelations = commodityRecordRelationService.lambdaQuery()
			.eq(CommodityRecordRelation::getCommodityRecordId, commodityRecordId).list();
		if (!commodityRecordRelations.isEmpty()) {
			String commodityNames = commodityRecordRelations.stream()
				.map(CommodityRecordRelation::getCommodityName)
				.collect(Collectors.joining(","));
			commodityRecord.setSummary(commodityNames);
			updateById(commodityRecord);
		} else {
			// 如果关联表没有数据，删除商品采购记录
			removeById(commodityRecordId);
		}
	}
}
